<template>
  <!--  -->

  <div style="">
    <el-row :gutter="24" style="height: 100vh; margin: 0; padding: 0;">
      <el-col :span="9" style="background-color: rgb(170, 219, 208) ;">
        <div style="background: url(/bg2.png) center no-repeat; height: 100%; background-size: 90% auto;"></div>
        <el-row style="position: absolute; top: 40px; left: 30px;"><el-text size="large" tag="b">Platform Manage
            Master</el-text></el-row>

      </el-col>
      <el-col :span="15">
        <el-row :gutter="24" style="">
          <el-col :span="10" :offset="7" style="display: flex; height: 100vh; align-items: center;">

            <el-form ref="formRef" :model="ruleForm" :rules="rules" label-width="0"
              style="max-width: 420px; padding: 2rem 3rem; border-radius: 5px; border: 1px solid rgb(232, 232, 231); box-shadow: 5px 5px 8px rgba(232, 232, 231, 0.5);">
              <div style="text-align: left;">
                <h2>账号登录</h2>
              </div>
              <el-form-item prop="username">
                <el-input size="large" v-model="ruleForm.username" placeholder="请输入用户名" clearable />
              </el-form-item>
              <el-form-item prop="password">
                <el-input size="large" type="password" v-model="ruleForm.password" placeholder="请输入密码" clearable
                  show-password />
              </el-form-item>

              <el-form-item prop="captcha">
                <el-row :gutter="24">
                  <el-col :span="14">
                    <el-input size="large" v-model="ruleForm.captcha" placeholder="请输入验证码" clearable />
                  </el-col>

                  <el-col :span="10" >
                    <div style="width: 100%;height: 32px;padding: 0;">

                      <el-image @click="onChangeCaptcha"
                        style="height: 32px; width: 80px; background-color: #eeeeee; border-radius: 3px;"
                        :src="captcha">
                        <template #error>
                          <div class="image-slot" style="font-size: 11px;">
                            点击刷新
                          </div>
                        </template>
                      </el-image>
                      <!-- <el-button link @click="onChangeCaptcha">换一张</el-button> -->
                    </div>
                    <el-progress style="width: 100%; margin-top: 5px;" :stroke-width="1" :percentage="captcha_timer"
                      :show-text="false" />
                  </el-col>
                </el-row>

              </el-form-item>

              <el-alert style="text-align: left; font-size: 12px;" v-show="result.show" type="error" :description="result.message" :closable="false"/>

              <el-form-item style="margin: 30px 0;">
                <el-button size="large" type="primary" @click="submitForm(formRef)" style="width: 100%; "
                  :disabled="onLogin">登录</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

  </div>

</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
import JSEncrypt from 'jsencrypt'
import axios from 'axios'
const encryptor = new JSEncrypt();

const captcha_timer = ref(0)
let timer = 0;
let timerHandler = 0;
let autoRefreshTime = 0;
const captchaExpiredSecs = 60;
const onLogin = ref(false)
const result = reactive({
  show: false,
  title: '',
  message: ''
});

const captcha = ref();
const router = useRouter()
const formRef = ref<FormInstance>()

interface RuleForm {
  username: string,
  password: string,
  captcha: string,
}

const ruleForm = reactive<RuleForm>({
  username: localStorage.getItem("login_username") || '',
  password: '',
  captcha: ''
});

const rules = reactive<FormRules<typeof ruleForm>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
  ],
})


// watch(()=> captcha.value , () => {
//   captcha_timer.value = 0;
// });

const update_session = (data: any) => {
  let keys = ['nonce', 'access_token', 'refresh_token', 'key'];
  for (let key of keys) {
    if (data[key]) {
      sessionStorage.setItem(key, data[key]);
    }
    //  else {
    //   sessionStorage.removeItem(key);
    // }
  }
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  result.show = false;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // console.log('submit!')
      onLogin.value = true;
      let data = {
        username: ruleForm.username,
        password: encryptor.encrypt(ruleForm.password),
        captcha: ruleForm.captcha
      };

      let ins = axios.create({
        headers: {
          'Nonce': sessionStorage.getItem("nonce")
        }
      });
      ins.post("/auth", data).then((rsp) => {
        let data = rsp.data;
        if (data['code'] != 200) {
          result.show = true;
          result.title = data['result'];
          result.message = data['message'];

          if (data['data']['captcha']) {
            captcha.value = data['data']['captcha'];
            captcha_timer.value = 0;
            timer = 0;
          }
          update_session(data['data']);

          onLogin.value = false;
        } else {
          localStorage.setItem("login_username", ruleForm.username);

          update_session(data['data']);
          clearInterval(timerHandler);
          router.push({ name: 'home' });
          // window.location.reload();
        }
      }).catch(error => {
        result.show = true;
        result.title = error['code'];
        result.message = error['message'];
        clearInterval(timerHandler);
        console.error(error);
      });
    } else {
      onLogin.value = false;
      console.log('error submit!', fields)
    }
  })
}

const onChangeCaptcha = () => {
  autoRefreshTime = 0;
  timer = 0;
  clearInterval(timerHandler);
  captcha.value = "";
  changeCaptcha();
  autoRefresh();
}


const changeCaptcha = () => {
  autoRefreshTime += 1;
  axios.get("/auth/captcha").then((rsp) => {
    let data = rsp.data['data'];
    captcha.value = data['captcha'];
    captcha_timer.value = 0;
    timer = 0;
    update_session(data);
  }).catch(error => {
    clearInterval(timerHandler);
    result.show = true;
    result.title = error['code'];
    result.message = error['message'];
    console.error(error);
  });
}

const autoRefresh = () => {
  timer = 0;

  timerHandler = setInterval(() => {
    timer += 1;
    let val = Math.ceil(100 / captchaExpiredSecs * timer);
    captcha_timer.value = val > 100 ? 100 : val;
    if (timer >= captchaExpiredSecs) {
      timer = 0;
      clearInterval(timerHandler);
      if (autoRefreshTime < 3) {
        changeCaptcha();
        autoRefresh();
      } else {
        captcha.value = "";
      }
    }
  }, 1000);
}

onMounted(() => {
  axios.get("/auth/prelude").then((rsp) => {
    let data = rsp.data['data'];
    captcha.value = data['captcha'];
    encryptor.setPublicKey(data['key']);
    update_session(data);
    autoRefresh();
  }).catch(error => {
    clearInterval(timerHandler);
    result.show = true;
    result.title = error['code'];
    result.message = error['message'];
    console.error(error);
  });
});


</script>



<style scoped>
.login-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}
</style>
